import { getToken } from "next-auth/jwt"
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"

export async function middleware(request: NextRequest) {
  const path = request.nextUrl.pathname
  
  // 定义公开路径
  const publicPaths = ["/auth/login", "/auth/register"]
  const isPublicPath = publicPaths.includes(path)

  const token = await getToken({
    req: request,
    secret: process.env.NEXTAUTH_SECRET
  })

  // 已登录用户访问登录/注册页面时重定向到首页
  if (isPublicPath && token) {
    return NextResponse.redirect(new URL("/", request.url))
  }

  // 未登录用户访问非公开页面时重定向到登录页
  if (!isPublicPath && !token && path !== "/") {  // 修改这里，允许访问根路径
    return NextResponse.redirect(new URL("/auth/login", request.url))
  }

  return NextResponse.next()
}

// 配置需要进行中间件检查的路径
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
} 